package org.example.book.strategy;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import org.example.book.state.pojo.Order;
import org.example.book.util.Constant;


/**
 * @author jeff
 */
public class AlipayStrategy implements PayStrategyInterface {
    @Override
    public String pay(Order order) {
        AlipayClient alipayClient = new DefaultAlipayClient(Constant.GATE_WAY,
                Constant.APP_ID, Constant.APP_PRI_KEY, "JSON", "UTF-8", Constant.APP_PUB_KEY, Constant.SIGN_TYPE);
        AlipayTradePagePayRequest alipayTradePagePayRequest = getAlipayTradePagePayRequest(order);
        try {
            return alipayClient.pageExecute(alipayTradePagePayRequest, "GET").getBody();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private AlipayTradePagePayRequest getAlipayTradePagePayRequest(Order order) {
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();
        alipayTradePagePayRequest.setReturnUrl(Constant.ALIPAY_CALLBACK_URL);
        alipayTradePagePayRequest.setBizContent(
                "{\"out_trade_no\":\"" + order.getOrderId() + "\"," +
                        "\"total_amount\":\"" + order.getPrice() + "\"," +
                        "\"subject\":\"" + "test" + "\"," +
                        "\"body\":\"商品描述\"," +
                        "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"" +
                        "}");
        return alipayTradePagePayRequest;
    }
}
